$(() => {
    load();
});
const reLoad = () => {
    $('#exampleTable').bootstrapTable('refresh')
}

const getOneAndTwo = () => {
    return new Promise((resolve, reject) => {
        let pData = {
            current: 1,
            size: 10000,
            field:"B4",
            status:"2"
        }
        $.ajax({
            type: 'post',
            data:   JSON.stringify(pData) ,
            contentType: 'application/json',
            url: '/getDecrypt',
            success: function (r) {
                if (r.code == 0) {
                    resolve(r.data.records)
                } else {
                    layer.msg(r.msg);
                    reject(r)
                }
            }
        });
    })
}

const EntryScore = async (item = null) => {
    console.log('=====>>录入分数>', item)
    let  myOption = '',   formitem = ''
    const oneAndTwoData = await getOneAndTwo()
    let oldmyOption1 =  '', oldmyOption2 =  '', oldmyOption3 =  ''
    for (let i = 0; i < oneAndTwoData.length; i++) {
        if (oneAndTwoData[i].num1s != '-') {
            if ( null != item && item.isEdit && item.num1 && item.num1==oneAndTwoData[i].num1s) {
                oldmyOption1 += ` <option value="${item.num1}" selected>${item.num1}</option>`
                oldmyOption2 += ` <option value="${item.num1}" disabled>${item.num1}</option>`
                oldmyOption3 += ` <option value="${item.num1}" disabled>${item.num1}</option>`
            }else if (null != item && item.isEdit && item.oneNum1  && item.oneNum1==oneAndTwoData[i].num1s) {
                oldmyOption1 += ` <option value="${item.oneNum1}" selected>${item.oneNum1}</option>`
                oldmyOption2 += ` <option value="${item.oneNum1}" disabled>${item.oneNum1}</option>`
                oldmyOption3 += ` <option value="${item.oneNum1}" disabled>${item.oneNum1}</option>`
            }else if (null != item && item.isEdit && item.twoNum1 && item.twoNum1==oneAndTwoData[i].num1s) {
                oldmyOption2 += ` <option value="${item.twoNum1}" selected>${item.twoNum1}</option>`
                oldmyOption1 += ` <option value="${item.twoNum1}" disabled>${item.twoNum1}</option>`
                oldmyOption3 += ` <option value="${item.twoNum1}" disabled>${item.twoNum1}</option>`
            }else if (null != item && item.isEdit && item.threeNum1  && item.threeNum1==oneAndTwoData[i].num1s) {
                oldmyOption3 += ` <option value="${item.threeNum1}" selected>${item.threeNum1}</option>`
                oldmyOption2 += ` <option value="${item.threeNum1}" disabled>${item.threeNum1}</option>`
                oldmyOption1 += ` <option value="${item.threeNum1}" disabled>${item.threeNum1}</option>`
            }else{
                oldmyOption1 += ` <option value="${oneAndTwoData[i].num1s}">${oneAndTwoData[i].num1s}</option>`
                oldmyOption2 += ` <option value="${oneAndTwoData[i].num1s}">${oneAndTwoData[i].num1s}</option>`
                oldmyOption3 += ` <option value="${oneAndTwoData[i].num1s}">${oneAndTwoData[i].num1s}</option>`
            }
        }
    }
    for (let i = 0; i < 1 ; i++) {
        if (i == 0 && null != item && item.isEdit && item.num1) {
            oldmyOption1 += ` <option value="${item.num1}" selected>${item.num1}</option>`
            oldmyOption2 += ` <option value="${item.num1}" disabled>${item.num1}</option>`
            oldmyOption3 += ` <option value="${item.num1}" disabled>${item.num1}</option>`
        }
        if (i == 0 && null != item && item.isEdit && item.oneNum1) {
            oldmyOption1 += ` <option value="${item.oneNum1}" selected>${item.oneNum1}</option>`
            oldmyOption2 += ` <option value="${item.oneNum1}" disabled>${item.oneNum1}</option>`
            oldmyOption3 += ` <option value="${item.oneNum1}" disabled>${item.oneNum1}</option>`
        }
        if (i == 1 && null != item && item.isEdit && item.twoNum1) {
            oldmyOption2 += ` <option value="${item.twoNum1}" selected>${item.twoNum1}</option>`
            oldmyOption1 += ` <option value="${item.twoNum1}" disabled>${item.twoNum1}</option>`
            oldmyOption3 += ` <option value="${item.twoNum1}" disabled>${item.twoNum1}</option>`
        }
        if (i == 2 && null != item && item.isEdit && item.threeNum1) {
            oldmyOption3 += ` <option value="${item.threeNum1}" selected>${item.threeNum1}</option>`
            oldmyOption2 += ` <option value="${item.threeNum1}" disabled>${item.threeNum1}</option>`
            oldmyOption1 += ` <option value="${item.threeNum1}" disabled>${item.threeNum1}</option>`
        }
    }
    for (let i = 0; i < 1 ; i++) {
        formitem += `
                      <div class="layui-form-item">
                            <label class="layui-form-label" style="width:auto;border: 0;">选手姓名</label>
                            <div class="layui-input-block">
<!--                            id-->
                                <input style="    display: none;" value="${(
            i == 0 ? (item?.oneId == null ? '' : item.oneId) : i == 1 ? (item?.twoId == null ? '' : item.twoId) : '') }"
                                name="${(i == 0 ? 'oneId' : i == 1 ? 'twoId' : '') }">
<!-- 名字-->
                                <input type="text" value="${ (
            i == 0 ? (item?.nameOne == null ? '' : item.nameOne) : i == 1 ? (item?.nameTwo == null ? '' : item.nameTwo) : (item?.nameThree == null ? '' : item.nameThree)
        ) }" disabled   name="${(
            i == 0 ? 'nameOne' : i == 1 ? 'nameTwo' : 'nameThree'
        )}"  placeholder="请输入" autoComplete="off" class="layui-input">

                            </div>
                            <div class="layui-input-inline" style="width: calc(100% - 111px); margin-left: 23px;  margin-right: 1px;">
                                <select name="num1s${i}" id="select${i}" lay-search="" lay-verify="required"  lay-filter="selectfilter${i}">
                                    <option value="">请选择一次加密序号</option>
                                    ${i == 0 ? oldmyOption1 : i == 1 ? oldmyOption2 : oldmyOption3}
                                </select>
                            </div>
                        </div>`
    }
    console.log('=item.threeNum1=', oldmyOption1, oldmyOption2, oldmyOption3)

    //姓名
   let toIndex = layer.open({
        type: 1,
        area: ['500px', '600px'],
        title: "信息录入",
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: `
<form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">

  <div class="layui-form-item">
        <label class="layui-form-label" style="width:auto;border: 0;">请仔细核对信息</label>
  </div>
   <div class="layui-form-item">
    <label class="layui-form-label" style="width:auto;border: 0;">检录序号</label>
     <div class="layui-input-block">
      <input type="text" name="recordNumber" value="${(null != item && item.recordNumber) ? item.recordNumber : '12'}" disabled lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
    </div>
  </div>
   <div class="layui-form-item">
    <label class="layui-form-label" style="width:auto;border: 0;">参赛单位</label>
     <div class="layui-input-block">
      <input type="text" name="unitName" value="${item?.unitName}" disabled  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
    </div>
  </div>
   ${formitem}
  <div class="layui-form-item" style="display: flex;    justify-content: center;">
    <button class="layui-btn" type="button"  lay-submit lay-filter="layedit-code-yes">提交</button>
  </div>
</form>
                `,
        success: (layero, index) => {
            layui.use(['form'], () => {
                setTimeout(()=>{
                    selectInput('select0',layero)
                },50)

                var form = layui.form;
                form.render('select');
                //获取所有select监听

                form.on('submit(layedit-code-yes)', async (data) => {
                    const mydata = data.field
                    console.log('提交数据', mydata, item)
                    //导入
                    let rqnumber = 0, existnumber = 0
                    if(mydata.num1s0==''){
                        layer.msg("参赛选手必须选择一次加密序号")
                        return false
                    }
                    if (typeof mydata.oneId != null && mydata.oneId !== '') {
                        existnumber++;
                        let othedata={
                            oneself :  mydata.num1s0==item.twoNum1
                        }
                        othedata=(item.isEdit || item.oneNum1) ?othedata:{}
                        await $.ajax({
                            type: 'get',
                            data: {
                                field:"B4",
                                status:2,
                                num1s: mydata.num1s0,
                                id: mydata.oneId,
                                ...othedata
                            },
                            contentType: 'application/json',
                            url: (item.isEdit || item.oneNum1) ? '/updateEncipher': '/updateStuCopy',
                            success: function (r) {
                                if (r.code == 0) {
                                    rqnumber++;
                                }
                            }
                        });
                    }
                    if (existnumber == rqnumber) {
                        layer.msg("成功")
                    } else {
                        layer.msg("失败" + (existnumber - rqnumber))
                    }
                    layer.close(index)
                    reLoad();



                });
            })


        }
    });

    layer.full(toIndex);


}

const derive = () => {
    console.log('=====>>导出>')
    layer.confirm(`是否导出婴幼儿早期发展赛场选手与一次加密信息？`, {
        btn1: function (index) {
            window.location.href = '/jzweb/zhiyeSignUpComReality/downloadStuDecrypt?field=B4&type=3&status=2';
            layer.close(index)
        }
    });
}

const edit = (mydata) => {
    console.log('=====>>修改>', mydata)
    mydata.isEdit = true
    EntryScore(mydata)
}

const reset = (mydata) => {
    console.log('=====>>重置>', mydata)
    layer.confirm(`是否重置${mydata.unitName}下选手已绑定的一次加密信息`, {
        btn1: function (index) {
            $.ajax({
                type: 'get',
                data: {
                    field:"B4",
                    unitName:mydata.unitName
                },
                contentType: 'application/json',
                url: '/resetDecrypt',
                success: function (r) {
                    if (r.code == 0) {
                        reLoad();
                        layer.msg('重置成功')
                        layer.close(index)
                    }else{
                        layer.msg(r.msg)
                    }
                }
            });

        }
    });
}

const columns =   [
    {
        field: 'recordNumber',
        title: '检录序号',
        width: '105px'
    },
    {
        field: 'unitName',
        title: '参赛单位',
        width: '105px'
    },
    {
        field: 'nameOne',
        title: '选手姓名',
        width: '105px'
    },
    {
        field: 'oneNum1',
        title: '一次加密号',
        width: '105px'
    },
    {
        title: '操作',
        field: 'id',
        align: 'center',
        // width:'50px',
        formatter: function (value, row, index) {
            return (row.oneNum1 == null && row.twoNum1 == null && row.threeNum1 == null) ? ` <a style="color: #18a689" class="${s_input_h}" href="#" mce_href="#" title="录入" onclick="EntryScore(${JSON.stringify(row).replace(/\"/g, "'")})">录入</a>` :
                `<a style="color: #18a689" class="${s_edit_h}" href="#" mce_href="#" title="修改" onclick="edit(${JSON.stringify(row).replace(/\"/g, "'")})">修改</a>
<a style="color: #a12c2c" class="${typeof reset1 =='undefined'?'hidden':''}" href="#" mce_href="#" title="重置" onclick="reset(${JSON.stringify(row).replace(/\"/g, "'")})">重置</a>`;
        },
        width: '230px'
    }
]
columns.forEach(item => {
    item.align = 'center'
    item.valign='middle'
})

function load() {
    $('#exampleTable')
        .bootstrapTable(
            {
                method: 'post', // 服务器数据的请求方式 get or post
                url: '/jzweb/zhiyeSignUpComReality/teamList', // 服务器数据的加载地址
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                //search : true, // 是否显示搜索框
                showColumns: false, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                queryParamsType: "",
                queryParams: function (params) {
                    console.log('params', params)
                    return {
                        current: params.pageNumber,
                        size: params.pageSize,
                        field:"B4",
                        status:"2"
                    };
                },
                responseHandler: function (res) {
                    if (res.code !== '0') {
                        layer.msg(res.msg);
                        return false
                    }
                    return {
                        "rows": res.data.records,
                        ...res.data
                    };
                },
                columns
            });
}